#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import oauth
import logging
import urllib, urllib2

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from django.utils import simplejson
from google.appengine.api import memcache
from util.InitDatabase import InitDatabase
from util.initItem import InitItem
#from util.models import History
from util.models import UserInfo
from util.models import UserFavoriteList
import string
import random
import ConfigParser
import datetime
import time

#webapp.template.register_template_library('japaneseFilter')

######## Need to Modify #########
CONSUMER_KEY = '57fce955677979ef7ce5'
CONSUMER_SECRET = '725999169e12efac670f0a1c22731853bd76cbed'
URL_SETTING_FILE = "urlSettings.ini"
LOAD_CONTENTS_NUM = 10
USER_HISTORY_NUM = 10
RECOMMEND_ITEM_NUM = 3
RECENT_SEC = 86400
#RECENT_SEC = 300
FAVORITE_MAX = 30
#################################

BASE_URL = 'http://api.mixi-platform.com/os/0.8'

# initialize application
class AppliInitialize(webapp.RequestHandler):
    def __init__(self):
        ############# Need to modify ##################
        self.QUESTION_MAX_NUM = 4
        self.QUESTION_MAX_VALUE = 4
        ###############################################
        self.SESSION_ID_LENGTH = 8
        self.URL_SETTING_FILE = "urlSettings.ini"
        self.MOBILE_TYPE = 'mobile'
        self.PC_TYPE = 'pc'
        self.SMARTPHONE_TYPE = 'smartphone'
        
            
    def get(self):
        # get userID
        ownerID = self.request.get('opensocial_owner_id')
        newVoiceText = self.request.get('newVoiceText')
        userAgent = detectAgent(self.request.user_agent)
        userID = self.request.get('userID')
        
        person=getUserInfo(ownerID)
        if person is not None:
            userIDs = person['entry']['id']
            userID = userIDs.split(":")[1]
            username = person['entry']['nickname']
            if username =='':
                username = 'anonymous'
        
#        userID = "abcdefg"
#        username = u"ほげってぃ"
        sessionID = userID + self.createSessionID()  
        conf = getURLConfiguration()
        voiceText = memcache.get("voice-" + sessionID)
        if voiceText is None:
            voiceText = ""
        voiceText = voiceText + newVoiceText
                      
        # create appli UI
        template_values = {
                           'imgRootURL':conf.get(userAgent, 'imgRootURL'),
                           'userID':userID,
 #                          'username':username,
                           'sessionID':sessionID,
                           'voiceText':voiceText,
                           'userAgent':userAgent,
                           'appRootURL':conf.get(userAgent, 'appRootURL'),
                           }
        path = os.path.join(os.path.dirname(__file__), './tmpl/top_o.html')
        self.response.out.write(template.render(path, template_values))

        
    '''       
    def getURLs(self, settingFile):
        conf = ConfigParser.SafeConfigParser()
        conf.read(settingFile)
        return conf
    '''    

    '''
    def getUserInfo(self, user_id):
        data = memcache.get('person-%s' % user_id)
        if data is not None:
            return data

        consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
        params = {'xoauth_requestor_id': user_id,
                  'format': 'json',
                  }

        request = oauth.OAuthRequest.from_consumer_and_token(
                  consumer,
                  http_method='GET',
                  http_url=BASE_URL + '/people/@me/@self',
                  parameters=params,
              )
        
        request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)

        uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
        r = urllib2.Request(uri, headers=request.to_header())

        try:
            data = simplejson.loads(urllib2.urlopen(r).read())
            memcache.add('person-%s' % user_id, data, 3600)
            return data
        except urllib2.HTTPError, e:
            logging.error(e)
            return False
        except:
            return False
    '''  
    
    def createSessionID(self):
        chars = string.ascii_letters + string.digits + '_'
        sessionID = "".join([ random.choice(chars) for i in range(self.SESSION_ID_LENGTH) ])
        return sessionID

    def createRandomList(self, elementMaxNum, elementMaxValue):
        randomNumList = []
        i = 0
        while i < elementMaxNum:
            qid = random.randint(0, elementMaxValue - 1)
            if qid not in randomNumList:
                randomNumList.append(qid)
                i += 1
        return randomNumList    
     
''' 
    def getURLConfiguration(self):
        conf = memcache.get('confURL')
        if conf is None:
            conf = self.getURLs(self.URL_SETTING_FILE)
            memcache.add('confURL', conf, 60)
        return conf
'''

# for Category Page
class CategoryRequest(webapp.RequestHandler):
    def get(self, *args):
        offsetStr = self.request.get('offset')
        userID = self.request.get('userID')
        userAgent = detectAgent(self.request.user_agent)
        userAgent = 'pc'
        conf = getURLConfiguration()
        message = ""
        templateName = ""

        if len(args) == 0:
            categories = db.GqlQuery("SELECT * FROM Category WHERE mCategoryID = 0 ORDER BY lCategoryID ASC")        
            template_values = {
                               'appRootURL':conf.get(userAgent, 'appRootURL'),
                               'imgRootURL':conf.get(userAgent, 'imgRootURL'),
                               'preURL':'/category/',
                               'itemList':categories,
                               'requestID':'categoryPage',
                               'userID':userID,
                               
                               }
            templateName = 'tmpl/searchPage.html'
        
        elif len(args) == 1 :
            categories = db.GqlQuery("SELECT * FROM Category WHERE lCategoryID = :1 ORDER BY mCategoryID ASC", int(args[0]))        
            template_values = {
                               
                               'preURL':'/category/' + args[0] + "/",
                               'categories':categories,
                               'lCategory':args[0],
                               'requestID':'categoryPage',
                               'userID':userID,
                               'message':message,
                               }
            templateName = 'tmpl/categoryPage.html'
        
        elif len(args) == 2:
            categories = db.GqlQuery("SELECT * FROM Category WHERE lCategoryID = :1 AND mCategoryID = :2 ", int(args[0]), int(args[1]))        
            category = categories.fetch(1)
            items = db.GqlQuery("SELECT * FROM ItemInfo WHERE lCategoryID = :1 AND mCategoryID = :2 AND itemID <= :3 ORDER BY itemID ASC", int(args[0]), int(args[1]), LOAD_CONTENTS_NUM)        
            favoriteList = getItemListWithFavorite(self, userID, items)
            
            template_values = {
                               'lCategoryID':category[0].lCategoryID,
                               'mCategoryID':category[0].mCategoryID,
                               'categoryValue':category[0].categoryValue,
                               'itemList':favoriteList,
                               'offset':LOAD_CONTENTS_NUM,
                               'requestID':'categoryPage',
                               'updateID':'updateItem',
                               'itemNum':LOAD_CONTENTS_NUM,
                               'userID':userID,
                               'message':message,
                               }
            templateName = 'tmpl/itemPage.html'
       
        else:
            offset = int(args[2]) + LOAD_CONTENTS_NUM
            items = db.GqlQuery("SELECT * FROM ItemInfo WHERE lCategoryID = :1 AND mCategoryID = :2 AND itemID > :3 AND itemID <= :4 ORDER BY itemID ASC", int(args[0]), int(args[1]), int(args[2]), offset)        
            favoriteList = getItemListWithFavorite(self, userID, items)
            template_values = {
                               'offset':offset,
                               'itemList':favoriteList,
                               'requestID':'categoryPage',
                               'updateID':'updateItem',
                               'itemNum':LOAD_CONTENTS_NUM,
                               'userID':userID,
                              }
#            templateName = 'tmpl/loadMoreContents.html'
            templateName = 'tmpl/itemPage.html'
            
        path = os.path.join(os.path.dirname(__file__), templateName)
        self.response.out.write(template.render(path, template_values))

        

### for Favorite Page
class FavoritePageRequest(webapp.RequestHandler):
    def get(self, *args):
        offsetStr = self.request.get('offset')
        userID = self.request.get('userID')
        ownerID = self.request.get('opensocial_owner_id')
        itemList = []
        message = ""

        userAgent = detectAgent(self.request.user_agent)
        conf = getURLConfiguration()

        ###
        #person=self.getUserInfo(ownerID)
        #if person is not None:
        #        userID = person['entry']['id']
        #        username = person['entry']['nickname']
        #        if username =='':
        #            username = 'anonymous'
   
#        conf = getURLConfiguration()

        if len(args) == 3:
            offset = int(args[2])
        else:
            offset = int(args[0])

        
        
        userFavoriteLists = db.GqlQuery("SELECT * FROM UserFavoriteList WHERE userID= :1", userID)  
        userFavoriteList = userFavoriteLists.fetch(1)
    
        if len(userFavoriteList) > 0:
            favoriteList = userFavoriteList[0].favoriteList
            offsetE = offset + LOAD_CONTENTS_NUM
            itemList = self.createItemList(favoriteList, offset, offsetE) 
        else:
            message = u"お気に入りが登録されていません"
            
        template_values = {
                           'maxFavoriteNum':FAVORITE_MAX,
                            'imgRootURL':conf.get(userAgent, 'imgRootURL'),
                            'userID':userID,
                            'itemList':itemList,
                            'offset':offset,
                            'requestID':'favoritePage',
                            'updateID':'updateItem',
                            'itemNum':LOAD_CONTENTS_NUM,
                            'message':message,
                            }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/favoritePage.html')
        self.response.out.write(template.render(path, template_values))

    def createItemList(self, favoriteList, offsetS, offsetE):
        itemList = []
        if offsetE > len(favoriteList):
            offsetE = len(favoriteList)
        focusFavoriteList = favoriteList[offsetS:offsetE]
        for fullItemID in focusFavoriteList:    
            itemInfos = db.GqlQuery("SELECT * FROM ItemInfo WHERE fullItemID = :1", fullItemID)  
            itemInfo = itemInfos.fetch(1)
            item = {
                  'lCategoryID':itemInfo[0].lCategoryID,
                  'mCategoryID':itemInfo[0].mCategoryID,
                  'itemID':itemInfo[0].itemID,
                  'itemValue':itemInfo[0].itemValue,
                  'isFavorite':True,
                  }
            itemList.append(item)
        return itemList
  
      
### for Favorite Page
'''
class FavoritePageRequestOld(webapp.RequestHandler):
    def get(self, *args):
        offsetStr = self.request.get('offset')
        userID = self.request.get('userID')
        ownerID = self.request.get('opensocial_owner_id')
        itemList = []
        message = ""

        userAgent = detectAgent(self.request.user_agent)    
        conf = getURLConfiguration()
        ###
        #person=self.getUserInfo(ownerID)
        #if person is not None:
        #        userID = person['entry']['id']
        #        username = person['entry']['nickname']
        #        if username =='':
        #            username = 'anonymous'
   
#        conf = getURLConfiguration()

        if len(args) == 3:
            offset = int(args[2])
        else:
            offset = int(args[0])

        
        favorites = db.GqlQuery("SELECT * FROM History WHERE userID= :1 AND isFavorite = True ORDER BY selectedTime DESC", userID)  
        favoriteList = favorites.fetch(LOAD_CONTENTS_NUM, offset)
        offset = offset + LOAD_CONTENTS_NUM
        if len(favoriteList) > 0:
            itemList = self.createItemList(favoriteList) 
        else:
            message = u"お気に入りが登録されていません"
            
        template_values = {
                            'imgRootURL':conf.get(userAgent, 'imgRootURL'),
                            'userID':userID,
                            'itemList':itemList,
                            'offset':offset,
                            'requestID':'favoritePage',
                            'updateID':'updateItem',
                            'itemNum':LOAD_CONTENTS_NUM,
                            'message':message,
                            }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/favoritePage.html')
        self.response.out.write(template.render(path, template_values))

    def createItemList(self, favoriteList):
        itemList = []
        for favoriteItem in favoriteList:
            lCategoryID = favoriteItem.lCategoryID
            mCategoryID = favoriteItem.mCategoryID
            itemID = favoriteItem.itemID
            fullItemID = str(lCategoryID) + "_" + str(mCategoryID) + "_" + str(itemID)
     
            itemInfos = db.GqlQuery("SELECT * FROM ItemInfo WHERE fullItemID = :1", fullItemID)  
            itemInfo = itemInfos.fetch(1)
            item = {
                  'lCategoryID':lCategoryID,
                  'mCategoryID':mCategoryID,
                  'itemID':itemID,
                  'itemValue':itemInfo[0].itemValue,
                  'isFavorite':favoriteItem.isFavorite,
                  }
            itemList.append(item)
        return itemList
'''      

### for Ranking Page
class RankingPageRequest(webapp.RequestHandler):
    def get(self, *args):
        offsetStr = self.request.get('offset')
        userID = self.request.get('userID')
        ownerID = self.request.get('opensocial_owner_id')

        userAgent = detectAgent(self.request.user_agent)
        conf = getURLConfiguration()

        if len(args) == 3:
            offset = int(args[2])
        else:
            offset = int(args[0])
            
        randInt = random.randint(1, 111)
        recommends = db.GqlQuery("SELECT * FROM ItemInfo WHERE itemID <= :1 AND selectedTime = 0 ORDER BY itemID DESC", randInt)  
        recommendList = recommends.fetch(RECOMMEND_ITEM_NUM)
        recommendListWzFavorite = getItemListWithFavorite(self, userID, recommendList)

        minSelectedTime = 1
        favorites = db.GqlQuery("SELECT * FROM ItemInfo WHERE selectedTime > :1 ORDER BY selectedTime DESC", minSelectedTime)  
#        favoriteList = favorites.fetch(LOAD_CONTENTS_NUM, offset)
        favoriteList = favorites.fetch(LOAD_CONTENTS_NUM-1)
        favoriteListWzFavorite = getItemListWithFavorite(self, userID, favoriteList)
        

        timeBehind = int(time.time()) - RECENT_SEC
        recentUses = db.GqlQuery("SELECT * FROM ItemInfo WHERE selectedDateInt > :1 ORDER BY selectedDateInt DESC", timeBehind)  
#        recentUseList = recentUses.fetch(LOAD_CONTENTS_NUM, offset)
        recentUseList = recentUses.fetch(LOAD_CONTENTS_NUM-1)
        recentUseListWzFavorite = getItemListWithFavorite(self, userID, recentUseList)
        offset = offset + LOAD_CONTENTS_NUM      
        
        template_values = {
                            'imgRootURL':conf.get(userAgent, 'imgRootURL'),
                           'userID':userID,
                           'appRootURL':conf.get(userAgent, 'appRootURL'),
                           'preURL':'/category/',
                           'recommendList':recommendListWzFavorite,
                            'itemList':favoriteListWzFavorite,
                            'recentUseList':recentUseListWzFavorite,
                            'offset':offset,
                            'requestID':'rankingPage',
                            'updateID':'updateItem',
                            'itemNum':LOAD_CONTENTS_NUM,
                            }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/rankingPage.html')
        self.response.out.write(template.render(path, template_values))

class DiagnosisPageRequest(webapp.RequestHandler):
    def get(self, *args):
        userID = self.request.get('userID')
        recentWordList = memcache.get(userID + '_rw')
        message = ""
        userAgent = detectAgent(self.request.user_agent)
        conf = getURLConfiguration()
        
        if recentWordList is None:
            userInfos = db.GqlQuery("SELECT * FROM UserInfo WHERE userID = :1", userID)        
            userInfo = userInfos.fetch(1)
            if len(userInfo) == 1:
                recentWordList = userInfo[0].recentUseWordKeys
            else:
                recentWordList = []
                userInfo = UserInfo(userID=userID, totalUseTime=1, lastPlayedDate=datetime.datetime.now(), recentUseWordKeys=[])
                userInfo.put()   
           
                
        
        if len(recentWordList) > 0:
            elements = []
            counts = []
            for wordKey in recentWordList:
                wordIDs = wordKey.split('_')
                if wordIDs[0] in elements:
                    index = elements.index(wordIDs[0])
                    counts[index] = counts[index] + 1
                else:
                    elements.append(wordIDs[0])
                    counts.append(1)
            maxUsedNum = max(counts)
            maxIndex = counts.index(maxUsedNum)
            mostUsedCategory = elements[maxIndex]
            
            diagnoses = db.GqlQuery("SELECT * FROM Diagnosis WHERE lCategoryID = :1", int(mostUsedCategory))        
            diagnosis = diagnoses.fetch(1)
            oppositeCategoryID = diagnosis[0].oppositeCategoryID 
            timeBehind = int(time.time()) - RECENT_SEC
            recommends = db.GqlQuery("SELECT * FROM ItemInfo WHERE lCategoryID = :1 AND selectedDateInt < :2 ORDER BY selectedDateInt ASC", oppositeCategoryID, timeBehind)  
            recommendList = recommends.fetch(RECOMMEND_ITEM_NUM)
            recommendListWzFavorite = getItemListWithFavorite(self, userID, recommendList)

            
            levelID = int(self.checkLevel(maxUsedNum))
            levels = db.GqlQuery("SELECT * FROM Level WHERE levelID = :1", levelID)        
            level = levels.fetch(1)
            

        
            template_values = {
                            'imgRootURL':conf.get(userAgent, 'imgRootURL'),
                               'userID':userID,
                               'updateID':'updateItem',
                               'lCategoryID':diagnosis[0].lCategoryID,
                               'diagnosis':diagnosis[0].diagnosis,
                               'lCategoryName':diagnosis[0].lCategoryName,
                               'oppositelCategory':diagnosis[0].oppositelCategory,
                               'levelName':level[0].levelName,
                               'message':message,
                               'itemList':recommendListWzFavorite,
                               }   
        else:
            template_values = {
                              'message':u"占い結果はまだ表示されません。一回以上顔文字を使ってからまた見てね。",
                              }     
                
        templateName = 'tmpl/diagnosisPage.html'
        path = os.path.join(os.path.dirname(__file__), templateName)
        self.response.out.write(template.render(path, template_values))
        
  
    def checkLevel(self, number):
        levels = [10, 7, 4, 1]
        for x in range(len(levels)):
            if number >= levels[x]:
                return x

class ItemUpdate(webapp.RequestHandler):
    def get(self, *args):      
        userID = self.request.get('userID')
        type = self.request.get('type')
        
        if type == "favorite":
            userFavorites = db.GqlQuery("SELECT * FROM UserFavoriteList WHERE userID = :1", userID)  
            userFavorite = userFavorites.fetch(1)
            fullItemID = args[0] + "_" + args[1] + "_" + args[2]
            if len(userFavorite) == 0: #initialize
                favoriteList = [fullItemID]
                userFavoriteList = UserFavoriteList(userID=userID, favoriteList=favoriteList)
                userFavoriteList.put()   
                
            else:
               
                favoriteList = userFavorite[0].favoriteList
                
                if fullItemID in favoriteList: # remove item from favoriteList
                    index = favoriteList.index(fullItemID)
                    favoriteList.pop(index)
                    userFavorite[0].put()
                    
                
                else: # add item to favoriteList
                    if len(favoriteList) < FAVORITE_MAX:
                        favoriteList.append(fullItemID)
                        userFavorite[0].put()
                    else:
                        self.response.out.write("0")
            

                                    
        else:
            
            ###########Need to check #################
            ### update ItemInfo
            items = db.GqlQuery("SELECT * FROM ItemInfo WHERE lCategoryID = :1 AND mCategoryID = :2 AND itemID = :3", int(args[0]), int(args[1]), int(args[2]))  
            item = items.fetch(1)
            item[0].selectedDate = datetime.datetime.now()
            item[0].selectedDateInt = int(time.time())
            item[0].selectedTime = item[0].selectedTime + 1
            item[0].put()
                
            ### update UserInfo
            fullItemID = args[0] + "_" + args[1] + "_" + args[2]
            userInfos = db.GqlQuery("SELECT * FROM UserInfo WHERE userID =:1", userID)  
            userInfo = userInfos.fetch(1)
            if len(userInfo) == 1: # there has already been the user's entry
                userInfo[0].totalUseTime = userInfo[0].totalUseTime + 1
                userInfo[0].lastPlayedDate = datetime.datetime.now()
                recentUseWordKeys = userInfo[0].recentUseWordKeys
                if len(recentUseWordKeys) >= USER_HISTORY_NUM:
                    recentUseWordKeys.pop(0)
                    
                recentUseWordKeys.append(fullItemID)
                userInfo[0].recentUseWordKeys = recentUseWordKeys
                userInfo[0].put()
                memcache.set(userID + '_rw', recentUseWordKeys)
                    
            else: # there is no the user's entry
                userInfo = UserInfo(userID=userID, totalUseTime=1, lastPlayedDate=datetime.datetime.now(), recentUseWordKeys=[fullItemID])
                userInfo.put()   
                
'''       
class ItemUpdateOld(webapp.RequestHandler):
    def get(self, *args):      
        userID = self.request.get('userID')
        type = self.request.get('type')

        userItems = db.GqlQuery("SELECT * FROM History WHERE userID = :1 AND lCategoryID = :2 AND mCategoryID = :3 AND itemID = :4", userID, int(args[0]), int(args[1]), int(args[2]))  
        userItem = userItems.fetch(1)

        if len(userItem) == 1:
            if type == "item":
                ### update History
                userItem[0].selectedTime = userItem[0].selectedTime + 1
                userItem[0].selectedDate = datetime.datetime.now()
                userItem[0].put()
                
                ### update ItemInfo
                items = db.GqlQuery("SELECT * FROM ItemInfo WHERE lCategoryID = :1 AND mCategoryID = :2 AND itemID = :3", int(args[0]), int(args[1]), int(args[2]))  
                item = items.fetch(1)
                item[0].selectedDate = datetime.datetime.now()
                item[0].selectedTime = item[0].selectedTime + 1
                item[0].put()
                
                ### update UserInfo
                fullItemID = args[0] + "_" + args[1] + "_" + args[2]
                userInfos = db.GqlQuery("SELECT * FROM UserInfo WHERE userID =:1", userID)  
                userInfo = userInfos.fetch(1)
                if len(userInfo) == 1:
                    userInfo[0].totalUseTime = userInfo[0].totalUseTime + 1
                    userInfo[0].lastPlayedDate = datetime.datetime.now()
                    recentUseWordKeys = userInfo[0].recentUseWordKeys
                    if len(recentUseWordKeys) == USER_HISTORY_NUM:
                        recentUseWordKeys.pop(0)
                    
                    recentUseWordKeys.append(fullItemID)
                    userInfo[0].recentUseWordKeys = recentUseWordKeys
                    userInfo[0].put()
                    memcache.set(userID + '_rw', recentUseWordKeys)
                    
                    
                else:
                    userInfo = UserInfo(userID=userID, totalUseTime=1, lastPlayedDate=datetime.datetime.now(), recentUseWordKeys=[fullItemID])
                    userInfo.put()   
                
                                  
            elif type == "favorite":
                if userItem[0].isFavorite == True:
                    userItem[0].isFavorite = False
                else:
                    userItem[0].isFavorite = True
                    
                userItem[0].put()
         
        else:
            isFavorite = False
            if type == "favorite":
                isFavorite = True
            userHistory = History(userID=userID, lCategoryID=int(args[0]), mCategoryID=int(args[1]), itemID=int(args[2]), selectedTime=1, selectedDate=datetime.datetime.now(), isFavorite=isFavorite)
            userHistory.put()  
'''          

'''
class PrivacyPolicy(webapp.RequestHandler):             
    def get(self):
        template_values = {}
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        path = os.path.join(os.path.dirname(__file__), 'tmpl/privacy_o.html')
        self.response.out.write(template.render(path, template_values))

class SupportBrowser(webapp.RequestHandler):             
    def get(self):
        template_values = {}
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        path = os.path.join(os.path.dirname(__file__), 'tmpl/supportBrowser_o.html')
        self.response.out.write(template.render(path, template_values))
'''

   
def getItemListWithFavorite(self, userID, itemList):
    itemListWithFavorite = []

    userFavoriteLists = db.GqlQuery("SELECT * FROM UserFavoriteList WHERE userID= :1", userID)  
    userFavoriteList = userFavoriteLists.fetch(1)
    if len(userFavoriteList) == 0:
        favoriteList = []
        userFavoriteList = UserFavoriteList(userID=userID, favoriteList=favoriteList)
        userFavoriteList.put()   

    else:
        favoriteList = userFavoriteList[0].favoriteList
    
    for item in itemList: # itemList is list of fullItemValue
        if item.fullItemID in favoriteList:
            isFavorite = True
        else:
            isFavorite = False
            
        
#        itemInfos = db.GqlQuery("SELECT * FROM ItemInfo WHERE fullItemID=:1", item.fullItemID)        
#        itemInfo = itemInfos.fetch(1)
  
        itemInfo = {
                    "lCategoryID":item.lCategoryID,
                    "mCategoryID":item.mCategoryID,
                    "itemID":item.itemID,
                    "itemValue":item.itemValue,
                    "isFavorite":isFavorite,
                    }
        itemListWithFavorite.append(itemInfo)    
    return itemListWithFavorite

'''
def getUserFavoriteList(self, userID, items):
    favoriteList = []#
    for item in items:
        lCategoryID = item.lCategoryID
        mCategoryID = item.mCategoryID
        itemID = item.itemID
        userHistories = db.GqlQuery("SELECT * FROM History WHERE userID=:1 AND lCategoryID = :2 AND mCategoryID = :3 AND itemID = :4", userID, lCategoryID, mCategoryID, itemID)        
        userHistory = userHistories.fetch(1)
        if len(userHistory) == 1:#
            isFavorite = userHistory[0].isFavorite
            
        else:
            isFavorite = False
        itemList = {
                    "lCategoryID":lCategoryID,
                    "mCategoryID":mCategoryID,
                    "itemID":itemID,
                    "itemValue":item.itemValue,
                    "isFavorite":isFavorite,
                    }
        favoriteList.append(itemList)
    return favoriteList
''' 


def detectAgent(userAgent):
    if userAgent.startswith('DoCoMo'):
        return 'mobile'  
    elif userAgent.startswith('KDDI-'):
        return 'mobile'
    elif userAgent.startswith('SoftBank'):
        return 'mobile'
    elif userAgent.startswith('Vodafone'):
        return 'mobile'
    elif userAgent.startswith('Mozilla/5.0 (Linux; U; Android 2.1'):
        return 'android2.1'
    elif userAgent.startswith('Mozilla/5.0 (iP'):
        return 'smartphone'
    elif userAgent.startswith('Mozilla/5.0 (Li'):
        return 'smartphone'
    else:
        return 'pc'

def checkBrowser(userAgent):
    if userAgent.startswith('Mozilla/5.0 (Linux; U; Android 2.1'):
        return False
    elif userAgent.startswith('Mozilla/5.0 (compatible; MSIE 9.0'):
        return False
    else:
        return True

def getURLConfiguration():
    conf = memcache.get('confURL')
    if conf is None:
        conf = ConfigParser.SafeConfigParser()
        conf.read(URL_SETTING_FILE)
        memcache.add('confURL', conf, 60)
    return conf 
  
def getUserInfo(user_id):
    data = memcache.get('person-%s' % user_id)
    if data is not None:
        return data

    consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
    params = {'xoauth_requestor_id': user_id,
              'format': 'json',
             }

    request = oauth.OAuthRequest.from_consumer_and_token(
                  consumer,
                  http_method='GET',
                  http_url=BASE_URL + '/people/@me/@self',
                  parameters=params,
              )
    request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)

    uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
    r = urllib2.Request(uri, headers=request.to_header())

    try:
        data = simplejson.loads(urllib2.urlopen(r).read())
        memcache.add('person-%s' % user_id, data, 3600)
        return data
    except urllib2.HTTPError, e:
        logging.error(e)
        return False
    except:
        return False

application = webapp.WSGIApplication([
        ('/init', AppliInitialize), ('/init/(.*)', AppliInitialize), ('/categoryPage/(.*)/(.*)/(.*)', CategoryRequest), ('/categoryPage/(.*)/(.*)', CategoryRequest), ('/categoryPage/(.*)', CategoryRequest), ('/categoryPage', CategoryRequest), ('/favoritePage/(.*)/(.*)/(.*)', FavoritePageRequest), ('/favoritePage/(.*)', FavoritePageRequest), ('/rankingPage/(.*)/(.*)/(.*)', RankingPageRequest), ('/rankingPage/(.*)', RankingPageRequest), ('/updateItem/(.*)/(.*)/(.*)', ItemUpdate), ('/diagnosisPage', DiagnosisPageRequest), ('/dbutil', InitDatabase), ('/dbutil/item/(.*)', InitItem)], debug=True)
#, ('/privacy', PrivacyPolicy), ('/browser', SupportBrowser)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
